Your First AI application¶
Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall application architecture. A large part of software development in the future will be using these types of models as common parts of applications.
In this project, you'll train an image classifier to recognize different species of flowers. You can imagine using something like this in a phone app that tells you the name of the flower your camera is looking at. In practice you'd train this classifier, then export it for use in your application. We'll be using this dataset from Oxford of 102 flower categories, you can see a few examples below.
The project is broken down into multiple steps:
- Load the image dataset and create a pipeline.
- Build and Train an image classifier on this dataset.
- Use your trained model to perform inference on flower images.
We'll lead you through each part which you'll implement in Python.
When you've completed this project, you'll have an application that can be trained on any set of labeled images. Here your network will be learning about flowers and end up as a command line application. But, what you do with your new skills depends on your imagination and effort in building a dataset. For example, imagine an app where you take a picture of a car, it tells you what the make and model is, then looks up information about it. Go build your own dataset and make something new.
Import Resources¶
# TODO: Make all necessary imports.
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow_hub as hub
import tensorflow_datasets as tfds
import json
import time
import os
2024-07-11 12:17:58.931432: I tensorflow/core/util/port.cc:111] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable `TF_ENABLE_ONEDNN_OPTS=0`. 2024-07-11 12:17:58.957069: E tensorflow/compiler/xla/stream_executor/cuda/cuda_dnn.cc:9342] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered 2024-07-11 12:17:58.957101: E tensorflow/compiler/xla/stream_executor/cuda/cuda_fft.cc:609] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered 2024-07-11 12:17:58.957122: E tensorflow/compiler/xla/stream_executor/cuda/cuda_blas.cc:1518] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered 2024-07-11 12:17:58.962207: I tensorflow/core/platform/cpu_feature_guard.cc:182] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations. To enable the following instructions: AVX2 AVX_VNNI FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.
import logging
logger = tf.get_logger()
logger.setLevel(logging.ERROR)
print('Using:')
print('\t\u2022 TensorFlow version:', tf.__version__)
print('\t\u2022 Running on GPU' if tf.test.is_gpu_available() else '\t\u2022 GPU device not found. Running on CPU')
Using: • TensorFlow version: 2.14.1 • Running on GPU
2024-07-11 12:18:00.074205: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:894] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero. See more at https://github.com/torvalds/linux/blob/v6.0/Documentation/ABI/testing/sysfs-bus-pci#L344-L355 2024-07-11 12:18:00.080943: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:894] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero. See more at https://github.com/torvalds/linux/blob/v6.0/Documentation/ABI/testing/sysfs-bus-pci#L344-L355 2024-07-11 12:18:00.084442: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:894] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero. See more at https://github.com/torvalds/linux/blob/v6.0/Documentation/ABI/testing/sysfs-bus-pci#L344-L355 2024-07-11 12:18:00.215847: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:894] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero. See more at https://github.com/torvalds/linux/blob/v6.0/Documentation/ABI/testing/sysfs-bus-pci#L344-L355 2024-07-11 12:18:00.218424: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:894] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero. See more at https://github.com/torvalds/linux/blob/v6.0/Documentation/ABI/testing/sysfs-bus-pci#L344-L355 2024-07-11 12:18:00.219842: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:894] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero. See more at https://github.com/torvalds/linux/blob/v6.0/Documentation/ABI/testing/sysfs-bus-pci#L344-L355 2024-07-11 12:18:00.221242: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1886] Created device /device:GPU:0 with 1214 MB memory: -> device: 0, name: NVIDIA GeForce RTX 3050 Laptop GPU, pci bus id: 0000:01:00.0, compute capability: 8.6
physical_devices = tf.config.list_physical_devices('GPU')
for device in physical_devices:
tf.config.experimental.set_memory_growth(device, True)
2024-07-11 12:18:00.226960: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:894] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero. See more at https://github.com/torvalds/linux/blob/v6.0/Documentation/ABI/testing/sysfs-bus-pci#L344-L355 2024-07-11 12:18:00.228489: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:894] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero. See more at https://github.com/torvalds/linux/blob/v6.0/Documentation/ABI/testing/sysfs-bus-pci#L344-L355 2024-07-11 12:18:00.229857: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:894] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero. See more at https://github.com/torvalds/linux/blob/v6.0/Documentation/ABI/testing/sysfs-bus-pci#L344-L355 2024-07-11 12:18:00.228489: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:894] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero. See more at https://github.com/torvalds/linux/blob/v6.0/Documentation/ABI/testing/sysfs-bus-pci#L344-L355 2024-07-11 12:18:00.229857: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:894] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero. See more at https://github.com/torvalds/linux/blob/v6.0/Documentation/ABI/testing/sysfs-bus-pci#L344-L355
Load the Dataset¶
Here you'll use tensorflow_datasets to load the Oxford Flowers 102 dataset. This dataset has 3 splits: 'train', 'test', and 'validation'. You'll also need to make sure the training data is normalized and resized to 224x224 pixels as required by the pre-trained networks.
The validation and testing sets are used to measure the model's performance on data it hasn't seen yet, but you'll still need to normalize and resize the images to the appropriate size.
# TODO: Load the dataset with TensorFlow Datasets.
splits = ['train', 'validation', 'test']
dataset, dataset_info = tfds.load('oxford_flowers102', as_supervised=True, with_info=True, split=splits)
# TODO: Create a training set, a validation set and a test set.
training_set, validation_set, test_set = dataset
2024-07-11 12:18:00.255353: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:894] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero. See more at https://github.com/torvalds/linux/blob/v6.0/Documentation/ABI/testing/sysfs-bus-pci#L344-L355 2024-07-11 12:18:00.259093: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:894] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero. See more at https://github.com/torvalds/linux/blob/v6.0/Documentation/ABI/testing/sysfs-bus-pci#L344-L355 2024-07-11 12:18:00.260768: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:894] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero. See more at https://github.com/torvalds/linux/blob/v6.0/Documentation/ABI/testing/sysfs-bus-pci#L344-L355 2024-07-11 12:18:00.262302: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:894] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero. See more at https://github.com/torvalds/linux/blob/v6.0/Documentation/ABI/testing/sysfs-bus-pci#L344-L355 2024-07-11 12:18:00.263797: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:894] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero. See more at https://github.com/torvalds/linux/blob/v6.0/Documentation/ABI/testing/sysfs-bus-pci#L344-L355 2024-07-11 12:18:00.265183: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1886] Created device /job:localhost/replica:0/task:0/device:GPU:0 with 1214 MB memory: -> device: 0, name: NVIDIA GeForce RTX 3050 Laptop GPU, pci bus id: 0000:01:00.0, compute capability: 8.6
Explore the Dataset¶
# TODO: Get the number of examples in each set from the dataset info.
train_number = dataset_info.splits['train'].num_examples
validation_number = dataset_info.splits['validation'].num_examples
test_number = dataset_info.splits['test'].num_examples
print(f"the number of training examples = {train_number}")
print(f"the number of validation examples = {validation_number}")
print(f"the number of testing examples = {test_number}")
# TODO: Get the number of classes in the dataset from the dataset info.
class_number = dataset_info.features['label'].num_classes
print(f"the number of classes = {class_number}")
the number of training examples = 1020 the number of validation examples = 1020 the number of testing examples = 6149 the number of classes = 102
# TODO: Print the shape and corresponding label of 3 images in the training set.
for image, label in training_set.take(3):
print("this image from the train set have the following information")
print(f"\t shape: {image.shape}")
print(f"\t label: {int(label)}")
this image from the train set have the following information shape: (500, 667, 3) label: 72 this image from the train set have the following information shape: (500, 666, 3) label: 84 this image from the train set have the following information shape: (670, 500, 3) label: 70
# TODO: Plot 1 image from the training set. Set the title
# of the plot to the corresponding image label.
for image, label in training_set.take(1):
print(image.shape)
image = image.numpy().squeeze()
label = label.numpy()
plt.imshow(image)
plt.title(label)
plt.show()
(500, 667, 3)
Label Mapping¶
You'll also need to load in a mapping from label to category name. You can find this in the file label_map.json. It's a JSON object which you can read in with the json module. This will give you a dictionary mapping the integer coded labels to the actual names of the flowers.
with open('label_map.json', 'r') as f:
class_names = json.load(f)
# TODO: Plot 1 image from the training set. Set the title
# of the plot to the corresponding class name.
for image, label in training_set.take(1):
image = image.numpy().squeeze()
label = label.numpy()
plt.imshow(image)
plt.title(class_names[str(label)])
plt.show()
Create Pipeline¶
batch_size = 32
image_size = 224
num_training_examples = len(training_set)
def format_image(image, label):
image = tf.cast(image, tf.float32)
image = tf.image.resize(image, (image_size, image_size))
image /= 255
return image, label
training_batches = training_set.shuffle(num_training_examples//4).map(format_image).batch(batch_size).prefetch(1)
validation_batches = validation_set.map(format_image).batch(batch_size).prefetch(1)
testing_batches = test_set.map(format_image).batch(batch_size).prefetch(1)
Build and Train the Classifier¶
Now that the data is ready, it's time to build and train the classifier. You should use the MobileNet pre-trained model from TensorFlow Hub to get the image features. Build and train a new feed-forward classifier using those features.
We're going to leave this part up to you. If you want to talk through it with someone, chat with your fellow students!
Refer to the rubric for guidance on successfully completing this section. Things you'll need to do:
- Load the MobileNet pre-trained network from TensorFlow Hub.
- Define a new, untrained feed-forward network as a classifier.
- Train the classifier.
- Plot the loss and accuracy values achieved during training for the training and validation set.
- Save your trained model as a Keras model.
We've left a cell open for you below, but use as many as you need. Our advice is to break the problem up into smaller parts you can run separately. Check that each part is doing what you expect, then move on to the next. You'll likely find that as you work through each part, you'll need to go back and modify your previous code. This is totally normal!
When training make sure you're updating only the weights of the feed-forward network. You should be able to get the validation accuracy above 70% if you build everything right.
Note for Workspace users: One important tip if you're using the workspace to run your code: To avoid having your workspace disconnect during the long-running tasks in this notebook, please read in the earlier page in this lesson called Intro to GPU Workspaces about Keeping Your Session Active. You'll want to include code from the workspace_utils.py module. Also, If your model is over 1 GB when saved as a checkpoint, there might be issues with saving backups in your workspace. If your saved checkpoint is larger than 1 GB (you can open a terminal and check with ls -lh), you should reduce the size of your hidden layers and train again.
# TODO: Build and train your network.
URL = "https://tfhub.dev/google/imagenet/mobilenet_v3_large_075_224/feature_vector/5"
feature_extractor = hub.KerasLayer(URL, input_shape=(image_size, image_size, 3))
feature_extractor.trainable = False
model = tf.keras.Sequential()
model.add(feature_extractor)
model.add(tf.keras.layers.Dense(512, activation='relu'))
model.add(tf.keras.layers.Dropout(0.3))
model.add(tf.keras.layers.Dense(128, activation='relu'))
model.add(tf.keras.layers.Dropout(0.3))
model.add(tf.keras.layers.Dense(class_number, activation='softmax'))
model.summary()
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
EPOCHS = 20
history = model.fit(training_batches,
epochs=EPOCHS,
validation_data=validation_batches)
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
keras_layer (KerasLayer) (None, 1280) 2731616
dense (Dense) (None, 512) 655872
dropout (Dropout) (None, 512) 0
dense_1 (Dense) (None, 128) 65664
dropout_1 (Dropout) (None, 128) 0
dense_2 (Dense) (None, 102) 13158
=================================================================
Total params: 3466310 (13.22 MB)
Trainable params: 734694 (2.80 MB)
Non-trainable params: 2731616 (10.42 MB)
_________________________________________________________________
Epoch 1/20
2024-07-11 12:18:04.092356: I tensorflow/compiler/xla/stream_executor/cuda/cuda_dnn.cc:442] Loaded cuDNN version 8700 2024-07-11 12:18:04.162299: I tensorflow/tsl/platform/default/subprocess.cc:304] Start cannot spawn child process: No such file or directory 2024-07-11 12:18:04.417386: I tensorflow/tsl/platform/default/subprocess.cc:304] Start cannot spawn child process: No such file or directory 2024-07-11 12:18:04.837963: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x7f4b643b91e0 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices: 2024-07-11 12:18:04.837985: I tensorflow/compiler/xla/service/service.cc:176] StreamExecutor device (0): NVIDIA GeForce RTX 3050 Laptop GPU, Compute Capability 8.6 2024-07-11 12:18:04.841419: I tensorflow/compiler/mlir/tensorflow/utils/dump_mlir_util.cc:269] disabling MLIR crash reproducer, set env var `MLIR_CRASH_REPRODUCER_DIRECTORY` to enable. 2024-07-11 12:18:04.907089: I ./tensorflow/compiler/jit/device_compiler.h:186] Compiled cluster using XLA! This line is logged at most once for the lifetime of the process.
32/32 [==============================] - 6s 87ms/step - loss: 4.4492 - accuracy: 0.0608 - val_loss: 3.8072 - val_accuracy: 0.2775 Epoch 2/20 32/32 [==============================] - 2s 73ms/step - loss: 3.1742 - accuracy: 0.3000 - val_loss: 2.3876 - val_accuracy: 0.5480 Epoch 3/20 32/32 [==============================] - 2s 74ms/step - loss: 2.0435 - accuracy: 0.5294 - val_loss: 1.5642 - val_accuracy: 0.6706 Epoch 4/20 32/32 [==============================] - 2s 75ms/step - loss: 1.3529 - accuracy: 0.6578 - val_loss: 1.2401 - val_accuracy: 0.7127 Epoch 5/20 32/32 [==============================] - 2s 74ms/step - loss: 0.9103 - accuracy: 0.7804 - val_loss: 0.9909 - val_accuracy: 0.7637 Epoch 6/20 32/32 [==============================] - 3s 76ms/step - loss: 0.7109 - accuracy: 0.8186 - val_loss: 0.8400 - val_accuracy: 0.7990 Epoch 7/20 32/32 [==============================] - 2s 75ms/step - loss: 0.4913 - accuracy: 0.8667 - val_loss: 0.8004 - val_accuracy: 0.7922 Epoch 8/20 32/32 [==============================] - 2s 75ms/step - loss: 0.3503 - accuracy: 0.9196 - val_loss: 0.7500 - val_accuracy: 0.7941 Epoch 9/20 32/32 [==============================] - 2s 76ms/step - loss: 0.3179 - accuracy: 0.9235 - val_loss: 0.7697 - val_accuracy: 0.7912 Epoch 10/20 32/32 [==============================] - 2s 75ms/step - loss: 0.2691 - accuracy: 0.9363 - val_loss: 0.6965 - val_accuracy: 0.8118 Epoch 11/20 32/32 [==============================] - 2s 76ms/step - loss: 0.2154 - accuracy: 0.9441 - val_loss: 0.6612 - val_accuracy: 0.8265 Epoch 12/20 32/32 [==============================] - 2s 75ms/step - loss: 0.1634 - accuracy: 0.9637 - val_loss: 0.6637 - val_accuracy: 0.8167 Epoch 13/20 32/32 [==============================] - 2s 75ms/step - loss: 0.1445 - accuracy: 0.9657 - val_loss: 0.6378 - val_accuracy: 0.8265 Epoch 14/20 32/32 [==============================] - 2s 75ms/step - loss: 0.1251 - accuracy: 0.9725 - val_loss: 0.6379 - val_accuracy: 0.8265 Epoch 15/20 32/32 [==============================] - 2s 74ms/step - loss: 0.1168 - accuracy: 0.9745 - val_loss: 0.6215 - val_accuracy: 0.8324 Epoch 16/20 32/32 [==============================] - 2s 74ms/step - loss: 0.0906 - accuracy: 0.9833 - val_loss: 0.6262 - val_accuracy: 0.8382 Epoch 17/20 32/32 [==============================] - 2s 74ms/step - loss: 0.1082 - accuracy: 0.9765 - val_loss: 0.6316 - val_accuracy: 0.8245 Epoch 18/20 32/32 [==============================] - 2s 75ms/step - loss: 0.0714 - accuracy: 0.9853 - val_loss: 0.6326 - val_accuracy: 0.8304 Epoch 19/20 32/32 [==============================] - 2s 75ms/step - loss: 0.0734 - accuracy: 0.9853 - val_loss: 0.6149 - val_accuracy: 0.8314 Epoch 20/20 32/32 [==============================] - 2s 75ms/step - loss: 0.0758 - accuracy: 0.9853 - val_loss: 0.6333 - val_accuracy: 0.8392
# TODO: Plot the loss and accuracy values achieved during training for the training and validation set.
training_accuracy = history.history['accuracy']
validation_accuracy = history.history['val_accuracy']
training_loss = history.history['loss']
validation_loss = history.history['val_loss']
epochs_range=range(EPOCHS)
plt.figure(figsize=(8, 8))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, training_accuracy, label='Training Accuracy')
plt.plot(epochs_range, validation_accuracy, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.subplot(1, 2, 2)
plt.plot(epochs_range, training_loss, label='Training Loss')
plt.plot(epochs_range, validation_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()
Testing your Network¶
It's good practice to test your trained network on test data, images the network has never seen either in training or validation. This will give you a good estimate for the model's performance on completely new images. You should be able to reach around 70% accuracy on the test set if the model has been trained well.
# TODO: Print the loss and accuracy values achieved on the entire test set.
(loss, accuracy) = model.evaluate(testing_batches)
print(f"the loss of the test set = {loss:.4f}")
print(f"the accurcy of the test set = {accuracy*100:.2f}%")
193/193 [==============================] - 7s 36ms/step - loss: 0.7838 - accuracy: 0.8018 the loss of the test set = 0.7838 the accurcy of the test set = 80.18%
Save the Model¶
Now that your network is trained, save the model so you can load it later for making inference. In the cell below save your model as a Keras model (i.e. save it as an HDF5 file).
# TODO: Save your trained model as a Keras model.
saved_h5_model_filepath = './my_model.h5'
tf.keras.models.save_model(model, filepath=saved_h5_model_filepath, save_format='h5')
/tmp/ipykernel_39164/2883968588.py:5: UserWarning: You are saving your model as an HDF5 file via `model.save()`. This file format is considered legacy. We recommend using instead the native Keras format, e.g. `model.save('my_model.keras')`.
tf.keras.models.save_model(model, filepath=saved_h5_model_filepath, save_format='h5')
Load the Keras Model¶
Load the Keras model you saved above.
# TODO: Load the Keras model
with tf.keras.utils.custom_object_scope({'KerasLayer': hub.KerasLayer}):
reloaded_keras_model = tf.keras.models.load_model(saved_h5_model_filepath)
reloaded_keras_model.summary()
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
keras_layer (KerasLayer) (None, 1280) 2731616
dense (Dense) (None, 512) 655872
dropout (Dropout) (None, 512) 0
dense_1 (Dense) (None, 128) 65664
dropout_1 (Dropout) (None, 128) 0
dense_2 (Dense) (None, 102) 13158
=================================================================
Total params: 3466310 (13.22 MB)
Trainable params: 734694 (2.80 MB)
Non-trainable params: 2731616 (10.42 MB)
_________________________________________________________________
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
keras_layer (KerasLayer) (None, 1280) 2731616
dense (Dense) (None, 512) 655872
dropout (Dropout) (None, 512) 0
dense_1 (Dense) (None, 128) 65664
dropout_1 (Dropout) (None, 128) 0
dense_2 (Dense) (None, 102) 13158
=================================================================
Total params: 3466310 (13.22 MB)
Trainable params: 734694 (2.80 MB)
Non-trainable params: 2731616 (10.42 MB)
_________________________________________________________________
Inference for Classification¶
Now you'll write a function that uses your trained network for inference. Write a function called predict that takes an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:
probs, classes = predict(image_path, model, top_k)
If top_k=5 the output of the predict function should be something like this:
probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163 0.01541934 0.01452626 0.01443549 0.01407339]
> ['70', '3', '45', '62', '55']
Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.
The predict function will also need to handle pre-processing the input image such that it can be used by your model. We recommend you write a separate function called process_image that performs the pre-processing. You can then call the process_image function from the predict function.
Image Pre-processing¶
The process_image function should take in an image (in the form of a NumPy array) and return an image in the form of a NumPy array with shape (224, 224, 3).
First, you should convert your image into a TensorFlow Tensor and then resize it to the appropriate size using tf.image.resize.
Second, the pixel values of the input images are typically encoded as integers in the range 0-255, but the model expects the pixel values to be floats in the range 0-1. Therefore, you'll also need to normalize the pixel values.
Finally, convert your image back to a NumPy array using the .numpy() method.
# TODO: Create the process_image function
def process_image(img):
return (tf.image.resize(tf.convert_to_tensor(img, dtype=tf.float32), (image_size, image_size))
/ 255) \
.numpy()
To check your process_image function we have provided 4 images in the ./test_images/ folder:
- cautleya_spicata.jpg
- hard-leaved_pocket_orchid.jpg
- orange_dahlia.jpg
- wild_pansy.jpg
The code below loads one of the above images using PIL and plots the original image alongside the image produced by your process_image function. If your process_image function works, the plotted image should be the correct size.
from PIL import Image
image_path = './test_images/hard-leaved_pocket_orchid.jpg'
im = Image.open(image_path)
image_tensor = np.asarray(im)
processed_test_image = process_image(image_tensor)
fig, (ax1, ax2) = plt.subplots(figsize=(10,10), ncols=2)
ax1.imshow(image_tensor)
ax1.set_title('Original Image')
ax2.imshow(processed_test_image)
ax2.set_title('Processed Image')
plt.tight_layout()
plt.show()
Once you can get images in the correct format, it's time to write the predict function for making inference with your model.
Inference¶
Remember, the predict function should take an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:
probs, classes = predict(image_path, model, top_k)
If top_k=5 the output of the predict function should be something like this:
probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163 0.01541934 0.01452626 0.01443549 0.01407339]
> ['70', '3', '45', '62', '55']
Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.
Note: The image returned by the process_image function is a NumPy array with shape (224, 224, 3) but the model expects the input images to be of shape (1, 224, 224, 3). This extra dimension represents the batch size. We suggest you use the np.expand_dims() function to add the extra dimension.
# TODO: Create the predict function
def predict(img_path, model, top_k):
im = Image.open(img_path)
image_tensor = (tf.image.resize(tf.convert_to_tensor(im, dtype=tf.float32), (image_size, image_size))
/ 255)
image_tensor = image_tensor[None, :, :, :]
ans = model.predict(image_tensor).squeeze()
probs = np.sort(ans)
classes = np.argsort(ans)
return probs[::-1][0:top_k], classes[::-1][0:top_k]
image_path = 'test_images/cautleya_spicata.jpg'
probs, classes = predict(image_path, model, 5)
1/1 [==============================] - 0s 348ms/step 1/1 [==============================] - 0s 348ms/step
Sanity Check¶
It's always good to check the predictions made by your model to make sure they are correct. To check your predictions we have provided 4 images in the ./test_images/ folder:
- cautleya_spicata.jpg
- hard-leaved_pocket_orchid.jpg
- orange_dahlia.jpg
- wild_pansy.jpg
In the cell below use matplotlib to plot the input image alongside the probabilities for the top 5 classes predicted by your model. Plot the probabilities as a bar graph. The plot should look like this:
You can convert from the class integer labels to actual flower names using class_names.
# TODO: Plot the input image along with the top 5 classes
test_dir = 'test_images/'
images_names = [file for file in os.listdir(test_dir) if file.lower().endswith('.jpg')]
top_k = 5
for image_name in images_names:
image_path = test_dir+image_name
probs, classes = predict(image_path, model, top_k)
classes_names = [class_names[f'{i}'] for i in classes]
fig, (ax1, ax2) =plt.subplots(figsize=(10,20), nrows=1, ncols=2)
plt.subplots_adjust(wspace=0.7)
img = Image.open(image_path)
image_arr = np.asarray(img)
ax1.imshow(image_arr)
ax1.set_title(os.path.splitext(image_name)[0])
ax2.barh(np.arange(top_k),probs)
ax2.set_aspect(0.1)
ax2.set_yticks(np.arange(top_k))
ax2.set_yticklabels(classes_names)
1/1 [==============================] - 0s 21ms/step 1/1 [==============================] - 0s 20ms/step 1/1 [==============================] - 0s 21ms/step 1/1 [==============================] - 0s 21ms/step